document.write("<script src='js/httpUtil.js'></script>");
document.write("<script src='js/common.js'></script>");
document.write("<script src='js/pagination.js'></script>");

var pageSize = 6;
var currentPage = 1;
$(document).ready(function () {
    //加载页面时执行
    accountList(1);
});

$("#keywordBtn").click(function () {
    //当点击搜索框按钮时执行
    accountList(1);
});

function accountList(currentPage) {
    this.currentPage = currentPage;
    // 获取关键字搜索框内容
    var keyword = $("#keyWord").val();
    var jsonObj = {"currentPage": currentPage, "pageSize": pageSize, "keyword": keyword};
    var result = httpPost(baseUrl + "/account/accountList", jsonObj);
    if (result.flag == 1) {
        //  初始化分页插件
        pagination(result.result.total, pageSize, currentPage, callback)
        //  查询账户列表
        var accountList = $('#accountList');
        accountList.empty();
        for (var i = 0; i < result.result.list.length; i++) {
            var account = result.result.list[i];
            //根据账户状态动态拼接按钮（启动，禁用）
            var editBtn = "<button class=\"btn btn-sm btn-primary m-b-5 m-t-5\" onclick='editAccountPanel(" + account.aid + ")'>编辑</button>"
            var enabledBtn = editBtn + " <button class=\"btn btn-sm btn-danger m-b-5 m-t-5\"" +
                "onclick='changeStatus(" + account.aid + ",0)'>禁用</button>";
            if (account.enabled != 1) {
                enabledBtn = editBtn + " <button class=\"btn btn-sm btn-info m-b-5 m-t-5\" " +
                    "onclick='changeStatus(" + account.aid + ",1)'>启用</button>";
            }

            // 将数据拼接到table上
            accountList.append("<tr class='text-center'>" +
                "<td>" + account.account + "</td>" +
                "<td>" + account.username + "</td>" +
                "<td>" + account.mobilephone + "</td>" +
                "<td>" + account.email + "</td>" +
                "<td>" + account.loginDate + "</td>" +
                "<td>" + account.department[0]+"..." + "</td>" +
                "<td>" + enabledBtn + "</td>" +
                "</tr>")
        }
    } else {
        toastr.error("系统错误", result.msg);
    }
}

function callback(targetPage, currentPage) {
    if (targetPage == 'prev') {
        accountList(currentPage - 1);
    } else if (targetPage == 'next') {
        accountList(currentPage + 1);

    }
}

$("#addAccountPanelBtn").click(function () {
    $("#addAccountModal :input").each(function () {
        $(this).val("");
    });
    var role = getRoleList("roleCheck");
    var department = getDepartmentList("departCheck");
    $('#roleList').html(role);
    $('#departmentList').html(department);

    //Flat purple color scheme for iCheck
    $('input[type="checkbox"].flat-purple, input[type="radio"].flat-purple').iCheck({
        checkboxClass: 'icheckbox_flat-purple',
        radioClass: 'iradio_flat-purple'
    })

    // 显示出新增账户的modal
    $('#addAccountModal').modal('show')
});

$("#addAccountBtn").click(function () {
    var account = $("#account").val();
    var userName = $("#userName").val();
    var password = $("#password").val();
    var userPhone = $("#userPhone").val();
    var userEmail = $("#userEmail").val();
    var roleList = getCheckValue("roleCheck")
    var departList = getCheckValue("departCheck")

    yorickAssert(account != "" && userName != "" && password != "" && userPhone != "" && userEmail != ""
        && roleList.length > 0 && departList.length > 0, "请输入完整参数", "参数错误")

    var jsonObj = {
        "account": account,
        "password": password,
        "username": userName,
        "mobilephone": userPhone,
        "email": userEmail,
        "roleList": roleList,
        "departmentList": departList
    };
    var result = httpPost(baseUrl + "/account/addAccount", jsonObj);
    if (result.flag == 1) {
        toastr.success("新增账户成功", "成功");
        $('#addAccountModal').modal('hide');
        accountList(1);
    } else {
        toastr.error("系统错误", result.msg);
    }
})

function changeStatus(aid, enabled) {
    var jsonObj = {"aid": aid, "enabled": enabled};
    var result = httpPost(baseUrl + "/account/accountStatus", jsonObj);
    if (result.flag == 1) {
        accountList(currentPage);
    } else {
        toastr.error("系统错误", result.msg);
    }
}

var editHead;
function editAccountPanel(aid) {
    var account = $("#editAccount");
    var userName = $("#editUserName");
    var userPhone = $("#editUserPhone");
    var userEmail = $("#editUserEmail");
    var password = $("#editPassword");
    var head = $("#editHead");
    $("#aid").val(aid)
    var jsonObj = {"aid": aid};
    var result = httpPost(baseUrl + "/account/accountDetail", jsonObj);
    if (result.flag == 1) {
        password.val("");
        account.val(result.result.account);
        userName.val(result.result.username);
        userPhone.val(result.result.mobilephone);
        userEmail.val(result.result.email);
        editHead = result.result.head;
        head.attr("src", imgUrl+editHead);
        var role = getRoleList("editRoleCheck");
        var department = getDepartmentList("editDepartCheck");
        $('#editRoleList').html(role);
        $('#editDepartmentList').html(department);

        var roleList = document.getElementsByName("editRoleCheck");
        for (var i = 0; i < roleList.length; i++) {
            for (var j = 0; j < result.result.roleList.length; j++) {
                if (result.result.roleList[j].roleId == roleList[i].value) {
                    roleList[i].checked = true;
                }
            }
        }

        var departmentList = document.getElementsByName("editDepartCheck");
        for (var i = 0; i < departmentList.length; i++) {
            for (var j = 0; j < result.result.departmentList.length; j++) {
                if (result.result.departmentList[j].did == departmentList[i].value) {
                    departmentList[i].checked = true;
                }
            }
        }

        enabledRadio("enabled",result.result.enabled)

        $('#editAccountModal').modal('show')
    } else {
        toastr.error("系统错误", result.msg);
    }
}

$("#editAccountBtn").click(function () {
    var aid = $("#aid").val();
    var account = $("#editAccount").val();
    var userName = $("#editUserName").val();
    var password = $("#editPassword").val();
    var userPhone = $("#editUserPhone").val();
    var userEmail = $("#editUserEmail").val();
    var roleList = getCheckValue("editRoleCheck");
    var departList = getCheckValue("editDepartCheck");
    var enabled = $('[name=enabled]:checked').val();
    yorickAssert(account != "" && userName != "" && userPhone != ""
        && roleList.length > 0 && departList.length > 0, "请输入完整参数", "参数错误")

    var jsonObj = {
        "aid": aid,
        "account": account,
        "password": password,
        "username": userName,
        "mobilephone": userPhone,
        "email": userEmail,
        "head": editHead,
        "roleList": roleList,
        "departmentList": departList,
        "enabled": enabled
    };

    var times=1;
    if(document.querySelector("#headInput").files.length!=0) {
        var head = new FormData(document.getElementById("form-uploadHead"));
        xhrpost(head, null,(data) => {
            times--;
            jsonObj["head"] = data;
        });
    }else{
        times=0;
    }
    var timer = setInterval(function(){
        if(times==0){
            clearInterval(timer);
            $("#spinner").fadeIn("slow");
            var result = httpPost(baseUrl + "/account/accountEdit", jsonObj);
            if (result.flag == 1) {
                toastr.success("修改账户成功", "成功");
                $('#editAccountModal').modal('hide');
                accountList(currentPage);
            } else {
                toastr.error("系统错误", result.msg);
            }
            $("#spinner").fadeOut("slow");
        }
    },1000);
})

function getRoleList(name) {
    //查询所有的角色列表
    var jsonObj = {"currentPage": 1, "pageSize": -1, "keyword": ""};
    var result = httpPost(baseUrl + "/role/roleList", jsonObj);
    var role = "";
    if (result.flag == 1) {
        for (var i = 0; i < result.result.list.length; i++) {
            role = role + "<label style='margin-left: 10px;'>" +
                "<input type=\"checkbox\" name='" + name + "' class=\"flat-purple\" value='" + result.result.list[i].roleId + "'>" +
                "<span style='margin-left: 5px;'>" + result.result.list[i].roleName + "</span>" +
                "</label>"
        }
    } else {
        toastr.error("系统错误", result.msg);
    }
    return role
}

function getDepartmentList(name) {
    //查询所有的机构列表
    var jsonObj = {"currentPage": 1, "pageSize": -1, "keyword": ""};
    var result = httpPost(baseUrl + "/department/departmentList", jsonObj);
    var department = "";
    if (result.flag == 1) {
        department = recursionDepartment(result.result.list, name)
    return department
    }
}

function recursionDepartment(departmentList, name){
    var department = "";
    for (var i = 0; i < departmentList.length; i++) {
        department = department + "<label style='margin-left: 10px;'>" +
            "<input type=\"checkbox\"  name='" + name + "' class=\"flat-purple\" value='" + departmentList[i].did + "'>" +
            "<span style='margin-left: 5px;'>" + departmentList[i].dname + "</span>" +
            "</label>"
        if (departmentList[i].children != null) {
            department = department + recursionDepartment(departmentList[i].children, name)
        }
    }
    return department;
}

//图片显示
document.querySelector("#headInput").onchange = function (){
    if(this.files.length){
        let file = this.files[0];
        let reader = new FileReader();
        //新建 FileReader 对象
        reader.onload = function(){
            // 当 FileReader 读取文件时候，读取的结果会放在 FileReader.result 属性中
            document.querySelector('#editHead').src = this.result;
        };
        // 设置以什么方式读取文件，这里以base64方式
        reader.readAsDataURL(file);
    }
}